<template>
  <div style="width: 100%;height: 100%">
    <!-- 查询框 -->
    <div>
      <el-select v-model="searchType" placeholder="请选择查询条件" style="width: 150px;">
        <el-option label="序号" value="id"></el-option>
        <el-option label="患者姓名" value="name"></el-option>
      </el-select>
      <el-input v-model="keyword" style="width: 300px; margin-left: 10px; margin-right: 10px" placeholder="请输入关键词"></el-input>
      <el-button type="primary" @click="searchPatients">查询</el-button>
      <el-button type="info" @click="reset">重置</el-button>
    </div>

    <!-- 操作框 -->
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="showAddDialog">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>

    <!-- 预约列表 -->
    <div class="table-container">
      <el-table :data="patients" stripe :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="id" label="患者序号"></el-table-column>
        <el-table-column prop="name" label="患者姓名"></el-table-column>
        <el-table-column prop="gender" label="患者性别"></el-table-column>
        <el-table-column prop="date_of_birth" label="患者出生日期"></el-table-column>
        <el-table-column prop="phone" label="手机号码"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="address" label="地址"></el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div style="margin-top: 20px; text-align: center;">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalItems">
      </el-pagination>

    <!-- 新增预约模态框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <el-form :model="editItem" label-width="100px">
        <el-form-item label="患者姓名">
          <el-input v-model="editItem.name"></el-input>
        </el-form-item>
        <el-form-item label="患者性别">
          <el-input v-model="editItem.gender"></el-input>
        </el-form-item>
        <el-form-item label="出生日期" prop="date_of_birth">
          <el-date-picker v-model="editItem.date_of_birth" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"></el-date-picker>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="editItem.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editItem.email"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="editItem.address"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSaveEdit">{{ isEditing ? '保存' : '新增' }}</el-button>
      </div>
    </el-dialog>
  </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      patients: [], // 预约列表数据
      currentPage: 1, // 当前页数
      pageSize: 5, // 每页显示的条数
      totalItems: 0, // 总条数
      searchType: 'id', // 默认查询类型
      keyword: '', // 查询关键词
      dialogVisible: false, // 账号信息模态框可见性
      editItem: {
        name: '',
        gender: '',
        date_of_birth: '',
        phone: '',
        email: '',
        address:'',
      },
      isEditing: false, // 是否为新增模式
    };
  },
  computed:{
    dialogTitle(){
      return this.isEditing ? '编辑信息' : '新增信息'; //false为新增，true为编辑
    }
  },
  mounted() {
    // 在组件加载完成后发送请求获取预约数据
    this.searchPatients();
  },
  methods: {
    // 获取预约数据
    searchPatients() {
      let url = 'http://localhost:8080/patients/selectAll';
      let params = {
        page: this.currentPage,
        size: this.pageSize,
      };

      if (this.keyword) {
        url = `http://localhost:8080/patients/selectBy${this.searchType}?${this.searchType}=${this.keyword}`;
      }

      axios.get(url, {params})
          .then(response => {
            const data = response.data.data;
            this.patients = data.list;
            this.totalItems = data.total;//记录获取的数量
          })
          .catch(error => {
            console.error('Error fetching appointments:', error);
          });
    },
    reset() {
      this.searchType = 'id';
      this.keyword = '';
      this.currentPage = 1;
      this.pageSize = 5;
      this.searchPatients();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.searchPatients();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.searchPatients();
    },
    handleSelectionChange(val) {//选择的行
      this.selectedRows = val.map(row => row.id);
    },
    showAddDialog() {
      this.isEditing = false;
      this.editItem = { // 新增表单置空
        name: '',
        gender: '',
        date_of_birth: '',
        phone: '',
        email: '',
        address:'',
      };
      this.dialogVisible = true;
    },
    closeDialog() {
      this.dialogVisible = false;
      this.isEditing = false;
    },
    handleAdd() {
      console.log(this.editItem)
      // 实现新增功能的逻辑
      axios.post("http://localhost:8080/patients/add", this.editItem)

          .then(response => {
            console.log(this.editItem)
            // 处理新增成功逻辑
            this.$message.success("新增成功");
            this.dialogVisible = false;
            this.searchPatients(); // 刷新数据
          })
          .catch(error => {
            // 处理新增失败逻辑
            console.error('Error adding new item:', error);
            this.$message.error("新增失败");
          });
    },
    handleEdit(row) {
      // 将选中行的数据赋值给编辑的数据项
      this.editItem = Object.assign({}, row);
      // 设置编辑状态为true
      this.isEditing = true; // 设置编辑状态为true，表示编辑
      // 打开新增/编辑弹窗
      this.dialogVisible = true;
    },
    handleSaveEdit() {
      // 发送编辑/新增请求到后端
      if (this.isEditing) {
        // 编辑状态下发送编辑请求
        axios.put("http://localhost:8080/patients/edit", this.editItem)
            .then(response => {
              // 处理编辑成功逻辑
              this.$message.success("编辑成功");
              this.closeDialog();
              this.searchPatients(); // 刷新数据
            })
            .catch(error => {
              // 处理编辑失败逻辑
              console.error('Error editing item:', error);
              this.$message.error("编辑失败");
            });
      } else {
        // 新增状态下发送新增请求
        this.handleAdd();
      }
    },
    handleDelete(id) {
      this.$confirm('此操作将永久删除该条目，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:8080/patients/delete/${id}`)
            .then(response => {
              this.$message.success('删除成功');
              this.searchPatients(); // 刷新数据
            })
            .catch(error => {
              console.error('Error deleting item:', error);
              this.$message.error('删除失败');
            });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    delBatch() {
      // 确认是否删除选中的行
      this.$confirm('此操作将永久删除所选条目，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 批量删除操作
        axios.delete(`http://localhost:8080/patients/deleteBatch`, {  data: this.selectedRows })
            .then(response => {
              this.$message.success('批量删除成功');
              this.searchPatients(); // 刷新数据
              this.selectedRows = []; // 清空选中的行
            })
            .catch(error => {
              console.error('Error deleting batch:', error);
              this.$message.error('批量删除失败');
            });
      }).catch(() => {
        this.$message.info('已取消批量删除');
      });
    }

  }
};
</script>
